<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/6/8
 * Time: 14:13
 */
namespace App\Listener;

use Swoole\Client;
use Swot\Server\Server;
use Swot\Event\Listener;
use Swot\Server\WebSocket\Connections;
use Swot\Server\WebSocket\WebSocketServer;

class WSMessageFrontListener extends Listener
{
    protected $name = 'ws.message.front';

    public function handler(WebSocketServer $swotServer = null, $swooleServer = null, $frame = null )
    {
         /*
            消息的格式 -》
            {
                'method' => //执行操作
                'msg' => 消息,
            }
         */

         $data = json_decode($frame->data, true);
         $this->{$data['method']}($swotServer, $swooleServer, $data, $frame->fd);
    }

    /**
     * 服务器广播
     *
     * @param  WebSocketServer $swotServer [description]
     */
    protected function serverBroadcast(WebSocketServer $swotServer, $swooleServer ,$data, $frame)
    {
        $config = $this->app->make('config');

        // 使用协程
        $cli = new \Swoole\Coroutine\Http\Client($config->get('server.route.server.host'), $config->get('server.route.server.port'));
        if ($cli->upgrade('/')) {
            $cli->push(json_encode([
                'method' => 'routeBroadcast',
                'msg'    => $data['msg'],
            ]));
        }
    }

    /**
     * 接收Route服务器的广播信息
     * @param  WebSocketServer $swotServer [description]
     */
    protected function routeBroadcast(WebSocketServer $swotServer, $swooleServer ,$data, $fd)
    {
        dd($data, 'server 中的 routeBroadcast');
        dd($fd, "server 中的 fd");
        $data['data']['user'] = 'test';

        $dataAck = [
            'method' => 'ack',
            'msg_id' => $data['msg_id']
        ];
        dd($dataAck);
        $swooleServer->push($fd, \json_encode($dataAck));

        $swotServer->sendAll(json_encode($data['data'], JSON_UNESCAPED_UNICODE));
    }

    /**
     * 接收客户端私聊的信息
     *
     * @param  WebSocketServer $swotServer [description]
     */
    protected function privateChat(WebSocketServer $swotServer, $swooleServer ,$data, $fd)
    {
        // 1. 获取私聊的id
        $clientId = $data['clientId'];
        // 2. 从redis中获取对应的服务器信息
        $clientIMServerInfoJson = $swotServer->getRedis()->hGet($this->app->make('config')->get('server.route.jwt.key'), $clientId);
        $clientIMServerInfo     = json_decode($clientIMServerInfoJson, true);
        dd($clientIMServerInfoJson, "接收方的服务器");

        // 3. 指定发送
        $request = Connections::get($fd)['request'];
        $token   = $request->header['sec-websocket-protocol'];

        // $url = '0.0.0.0:9000"
        $clientIMServerUrl = explode(":", $clientIMServerInfo);
        $swotServer->send($clientIMServerUrl[0], $clientIMServerUrl[1], [
            'method' => 'forwarding',
            'msg' => $data['msg'],
            'fd' => $clientIMServerInfo['fd']
        ], [
            'sec-websocket-protocol' => $token
        ]);
    }

    /**
     * 转发私聊信息
     * @param  WebSocketServer $swotServer [description]
     */
    protected function forwarding(WebSocketServer $swotServer, $swooleServer ,$data, $fd)
    {
        $swooleServer->push($data['fd'], json_encode(['msg' => $data['msg']], JSON_UNESCAPED_UNICODE));
    }
}